<?php

class App_Model_DbTable_User_Description extends Ext_Db_Table  
{  

    protected $_name = 'user_description';
    
    private static $_userDescription = array();
    
    public function getRowByUserId($userId)
    {    
        if(!$userId)
        {
            return "";
        }
        
        if(isset(self::$_userDescription['userId'][$userId]))
        {
            return self::$_userDescription['userId'][$userId];
        }
        
        $db = $this->getAdapter();
        $safe = $db->quoteInto(" userId = ? ", $userId);
        $row = $this->fetchRow($safe);
        if (!$row) {
            return "";
        }
        $userDescription = $row->toArray();
        
        self::$_userDescription['userId'][$userId] = $userDescription;
        
        return $userDescription;
    }
    
    public function addNew($inputArray)
    {
        $row = array();
        if(array_key_exists('userId', $inputArray)) $row['userId'] = $inputArray['userId'];
        if(array_key_exists('description', $inputArray)) $row['description'] = $inputArray['description'];
        
        try {
            // 插入数据行并返回插入的行数
            $rows_affected = $this->insert($row);
            // 最后插入的数据id   
            $last_insert_id = $this->getAdapter()->lastInsertId();
        }catch (Exception $e){
            trigger_error($e->getMessage(), E_USER_WARNING);
        }
        return $last_insert_id;
    }
    
    public function addOld($inputArray, $userId)
    {
        $sql_data_array = array();
        if(array_key_exists('description', $inputArray)) $sql_data_array['description'] = $inputArray['description'];
        if(!$sql_data_array){
            return "";
        }
        
        try {
            $db = $this->getAdapter();
            $where = $db->quoteInto(" userId = ? ", $userId);
            $rows_affected = $this->update($sql_data_array, $where);
            if($rows_affected){
                $this->_unsetRow($userId);
            }
        }catch (Exception $e){
            trigger_error($e->getMessage(), E_USER_WARNING);
        }
        
        return "";
    }
    
    private function _unsetRow($userId)
    {
        if(!$userId)
        {
            return "";
        }
        
        $userDescription = $this->getRowByUserId($userId);
        if(!$userDescription)
        {
            return "";
        }
        unset(self::$_userDescription['userId'][$userId]);
    }
}  

